#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.db import connection
from web.dao.base_dao import BaseDao
from web.models.stock_index_week import StockIndexWeek

"""
StockIndexWeek的dao类
"""


class StockIndexWeekDao(BaseDao):
    model_class = StockIndexWeek

    def find_begin_data_and_end_date_between_and_order_by(self, begin_date, end_date):
        """
        根据开始时间和结束时间查询开始时间和结束时间列表，并按照开始时间升序排列
        """

        with connection.cursor() as cursor:
            cursor.execute("select siw.begin_date, siw.end_date from stock_index_week siw "
                           "where siw.begin_date>=to_date(%s,'yyyy-mm-dd') "
                           "and siw.end_date<=to_date(%s,'yyyy-mm-dd') and siw.code_=000001 "
                           "order by siw.begin_date asc", (begin_date, end_date))
            begin_date_and_end_date_tuple = cursor.fetchall()
            return begin_date_and_end_date_tuple

    def find_max_end_date_and_min_begin_date_between(self, begin_date, end_date, n_date):
        """
        查询开始时间和结束时间之前的（包括开始时间和结束时间），n_date个交易日期中，最小的开始时间和最大的结束时间
        """

        with connection.cursor() as cursor:
            cursor.execute("select min(t.begin_date), max(t.end_date) from ( "
                           "select siw.begin_date, siw.end_date "
                           "from stock_index_week siw "
                           "where siw.begin_date<=to_date(%s,'yyyy-mm-dd') and siw.end_date<=to_date(%s,'yyyy-mm-dd') "
                           "and siw.code_=000001 "
                           "order by siw.begin_date desc) t "
                           "where rownum<=%s", (begin_date, end_date, n_date))
            min_begin_date_and_max_end_date_tuple = cursor.fetchall()
            return min_begin_date_and_max_end_date_tuple
